<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">宠友圈后台</h2>
      <el-form :model="loginForm" ref="loginFormRef" label-width="80px" class="login-form" :rules="loginRules">
        <el-form-item label="用户ID" prop="userinfoId">
          <el-input v-model="loginForm.userinfoId" placeholder="请输入用户ID"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          <router-link to="/register" class="register-link">注册账号</router-link>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" class="login-btn" :loading="authStore.loading">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../../store/modules/auth'
import { ElMessage } from 'element-plus'
import authApi from '../../api/auth'

const router = useRouter()
const authStore = useAuthStore()
const loginFormRef = ref(null)

// 角色路由映射
const roleIdToRoute = {
  '4': '/super-admin/user-manage',
  '3': '/merchant/product-manage',
  '2': '/doctor/doctor-info'
}

// 登录表单 + 校验规则
const loginForm = reactive({
  userinfoId: '',
  password: '',
  remember: false
})

// const loginRules = reactive({
//   userinfoId: [
//     { required: true, message: '请输入用户ID', trigger: 'blur' },
//     { type: 'number', message: '用户ID必须是数字', trigger: 'blur' }
//   ],
//   password: [
//     { required: true, message: '请输入密码', trigger: 'blur' },
//     { min: 3, max: 20, message: '密码长度在 3-20 之间', trigger: 'blur' }
//   ]
// })

// 登录处理（新增 avatar 字段传递）
const handleLogin = async () => {
  try {
    // 1. 表单校验
    await loginFormRef.value.validate()

    // 2. 提交登录接口
    const loginParams = {
      userinfoId: Number(loginForm.userinfoId),
      password: loginForm.password
    }
    const res = await authApi.login(loginParams)
    console.log('登录响应：', res)

    // 3. 响应判断
    if (res.code === 200 && res.data) {
      const { userinfoId, roleId, nickName, status, avatar } = res.data // 解构新增的 avatar

      // 校验核心字段
      if (!userinfoId || !roleId || !status) {
        ElMessage.error('登录失败：用户核心信息缺失')
        return
      }

      // 4. 存储状态（包含 avatar）
      authStore.login({ userinfoId, roleId, nickName, status, avatar })

      // 5. 记住密码逻辑
      if (loginForm.remember) {
        localStorage.setItem('rememberUser', JSON.stringify({
          userinfoId: loginForm.userinfoId,
          password: loginForm.password
        }))
      } else {
        localStorage.removeItem('rememberUser')
      }

      // 6. 校验用户状态
      if (status !== 1) {
        ElMessage.error('账号已禁用，请联系管理员')
        authStore.clearUserState()
        return
      }

      // 7. 角色跳转
      const targetRoute = roleIdToRoute[roleId.toString()]
      if (targetRoute) {
        ElMessage.success(`欢迎回来，${nickName}！`)
        await router.push(targetRoute)
      } else {
        ElMessage.warning(`暂无角色【${roleId}】对应的访问权限`)
        authStore.logout()
      }
    } else {
      ElMessage.error(res.message || '登录失败')
    }
  } catch (error) {
    if (error.name === 'ValidationError') return
    const errorMsg = error.message || '登录失败，请重试'
    ElMessage.error(errorMsg)
    console.error('登录异常：', error)
  }
}

// 页面挂载填充记住的账号密码
onMounted(() => {
  const rememberUser = localStorage.getItem('rememberUser')
  if (rememberUser) {
    try {
      const user = JSON.parse(rememberUser)
      loginForm.userinfoId = user.userinfoId || ''
      loginForm.password = user.password || ''
      loginForm.remember = true
    } catch (error) {
      console.error('解析记住的用户信息失败：', error)
      localStorage.removeItem('rememberUser')
    }
  }
})
</script>

<style scoped lang="scss">
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;

  .login-card {
    width: 420px;
    padding: 30px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .login-title {
      text-align: center;
      margin-bottom: 20px;
      color: #1989fa;
      font-size: 20px;
      font-weight: 600;
    }

    .login-form {
      .register-link {
        float: right;
        color: #1989fa;
        text-decoration: none;
      }

      .login-btn {
        width: 100%;
      }
    }
  }
}
</style>